<template>
  <div class="addModal">
    <el-form style="width: 50%; margin-left: 5%" :model="ruleForm" :rules="openRules" ref="ruleForm" label-width="100px"
      class="demo-ruleForm">
      <el-form-item label="优惠券名称" prop="name">
        <el-input size="mini" clearable v-model="ruleForm.name"></el-input>
      </el-form-item>
      <el-form-item label="介绍" prop="desc">
        <el-input size="mini" clearable v-model="ruleForm.desc"></el-input>
      </el-form-item>
      <el-form-item label="标签" prop="tag">
        <el-input size="mini" clearable v-model="ruleForm.tag"></el-input>
      </el-form-item>
      <el-form-item label="最低消费" prop="min">
        <el-input size="mini" clearable v-model="ruleForm.min">
          <template slot="append">元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="满减金额" prop="discount">
        <el-input size="mini" clearable v-model="ruleForm.discount">
          <template slot="append">元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="每人限领" prop="limit">
        <el-input size="mini" clearable v-model="ruleForm.limit">
          <template slot="append">张</template>
        </el-input>
      </el-form-item>
      <el-form-item label="分发类型" prop="type">
        <el-select v-model="ruleForm.type" placeholder="请选择">
          <el-option label="通用领劵" :value="0"></el-option>
          <el-option label="注册赠券" :value="1"></el-option>
          <el-option label="兑换码" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="优惠券数量" prop="total">
        <el-input size="mini" clearable v-model="ruleForm.total">
          <template slot="append">张</template>
        </el-input>
      </el-form-item>
      <el-form-item label="优惠券数量" prop="days">
        <el-radio-group size="mini" v-model="tabPosition" style="margin-bottom: 5px">
          <el-radio-button size="mini" label="0">领劵相对天数</el-radio-button>
          <el-radio-button size="mini" label="1">指定绝对时间</el-radio-button>
        </el-radio-group>
        <div v-if="tabPosition == 0">
          <el-input size="mini" clearable v-model="ruleForm.days">
            <template slot="append">天</template>
          </el-input>
        </div>
        <div v-else style="display: flex">
          <el-date-picker size="mini" v-model="ruleForm.startTime" type="datetime" placeholder="选择日期时间">
          </el-date-picker>至
          <el-date-picker size="mini" v-model="ruleForm.endTime" type="datetime" placeholder="选择日期时间">
          </el-date-picker>
        </div>
      </el-form-item>
      <el-form-item label="商品限制范围">
        <el-radio-group size="mini" v-model="tabPositionTwo" style="margin-bottom: 5px">
          <el-radio-button size="mini" label="0">全场通用</el-radio-button>
          <el-radio-button size="mini" label="1">指定分类</el-radio-button>
          <el-radio-button size="mini" label="2">指定商品</el-radio-button>
        </el-radio-group>
        <div v-if="tabPositionTwo == 1">
          <div>
            <el-cascader size="mini" v-model="input1" :options="options1" :props="cascaderProps"></el-cascader>
            <el-button size="mini" @click="handleSouSuo1">搜索</el-button>
          </div>
          <div>
            <el-table :data="table1" border style="width: 100%">
              <el-table-column align="center" prop="keywords" label="分类名称">
                <!-- <template v-slot="{ row }">
                  {{ row.keywords }}>{{ row.children.name }}
                </template> -->
              </el-table-column>
              <el-table-column align="center" label="操作">
                <template slot-scope="scope">
                  <el-tag @click="del(1, scope.$index)" type="danger">删除</el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div v-if="tabPositionTwo == 2">
          <el-select size="mini" v-model="input2" placeholder="请选择">
            <el-option v-for="(item, index) in options2" :key="index" :label="item.name" :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 15px">NO.{{ item.goodsSn }}</span>
            </el-option>
          </el-select>
          <el-button size="mini" @click="handleSouSuo2">搜索</el-button>
          <div>
            <el-table :data="table2" border style="width: 100%">
              <el-table-column align="center" prop="name" label="商品名称">
              </el-table-column>
              <el-table-column align="center" prop="goodsSn" label="商品编号">
              </el-table-column>
              <el-table-column align="center" label="操作">
                <template slot-scope="scope">
                  <el-tag @click="del(2, scope.$index)" type="danger">删除</el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <div style="text-align: right">
      <el-button :disabled="disabled" type="primary" size="mini" @click="submitForm('ruleForm')">确定</el-button>

      <el-button size="mini" @click="$emit('modalCancelEmit')">取消</el-button>
    </div>
  </div>
</template>

<script>
import { openRules } from './config'
import { getToken } from '@/utils/auth'
import moment from 'moment'
import {
  Couponcreate,
  Categorylist,
  Goodslist
} from '@/api/tggl/yhjgl'
export default {
  props: {
    // currentRow: '' //不严谨
    // 严谨
    // currentRow: {
    //   type: Object,
    //   default: ''
    // }
  },
  data() {
    return {
      headers: {
        'X-Litemall-Admin-Token': getToken()
      },
      openRules, //引入规则
      disabled: false,
      imageUrl: '',
      tabPosition: '0',
      tabPositionTwo: '0',
      ids: '',
      action: 'http://admin.bsmall.byesame.com/admin/storage/create',
      table1: [],
      table2: [],
      tableID1: [],
      tableID2: [],
      input1: null,
      input2: null,
      options1: [],
      options2: [],
      // 配置级联选择器的 props，指定子选项字段为 children
      cascaderProps: {
        label: 'name',
        value: 'id',
        children: 'children'
      },
      ruleForm: {
        name: null, //
        desc: null, //
        tag: null, //
        min: 0, //
        discount: 0, //
        limit: 1, //
        type: 0, //
        status: 0, //
        total: 0, //
        days: 0, //
        goodsValue: [], //
        goodsType: 0, //012
        endTime: null, //
        startTime: null, //
        timeType: 0 //有时间1没时间0
      },
      rules: {
        name: [
          { required: true, message: '优惠卷名称不能为空', trigger: 'blur' }
        ]
      }
    }
  },

  mounted() {
    Categorylist().then((res) => {
      console.log(res)
      this.options1 = res.data.list
    })
    Goodslist({ limit: 0 }).then((res) => {
      console.log(res)
      this.options2 = res.data.list
    })
  },
  methods: {
    del(i, index) {
      if (i == 1) {
        this.table1.splice(index, 1)
      } else {
        this.table2.splice(index, 1)
      }
    },
    handleSouSuo1() {
      console.log(this.input1)

      if (this.input1 == null) {
        this.$message({
          message: '请先选择商品',
          type: 'warning'
        })
      } else {
        const lastElement = this.input1[0]
        const selectedItem = this.options1.find(
          (item) => item.id === lastElement
        )
        this.table1.push(selectedItem) //id的那一行
        this.tableID1.push(this.input1[this.input1.length - 1]) //id是个数组的最后一个id

        this.input1 = null
      }
    },
    handleSouSuo2() {
      if (this.input2 == null) {
        this.$message({
          message: '请先选择商品',
          type: 'warning'
        })
      } else {
        const lastElement = this.input2
        const selectedItem = this.options2.find(
          (item) => item.id === lastElement
        )
        console.log(selectedItem)
        this.table2.push(selectedItem) //id的那一行
        this.tableID2.push(this.input2) //id
        this.input2 = null
      }
    },
    submitForm(formName) {
      console.log(this.table1)
      console.log(this.table2)

      if (Number(this.tabPositionTwo) == 1) {
        this.ruleForm.goodsValue = this.tableID1
      }
      if (Number(this.tabPositionTwo) == 2) {
        this.ruleForm.goodsValue = this.tableID2
      }
      if (Number(this.tabPostabPositionTwoition) == 0) {
        this.ruleForm.goodsValue = []
      }
      this.ruleForm.timeType = Number(this.tabPosition)
      this.ruleForm.goodsType = Number(this.tabPositionTwo)
      this.ruleForm.startTime = this.ruleForm.startTime
        ? moment(Number(this.ruleForm.startTime)).format('YYYY-MM-DD hh:mm:ss')
        : ''
      this.ruleForm.endTime = this.ruleForm.endTime
        ? moment(Number(this.ruleForm.startTime)).format('YYYY-MM-DD hh:mm:ss')
        : ''
      console.log(this.ruleForm.endTime)

      if (this.disabled) return
      this.disabled = true
      this.$refs[formName].validate((valid) => {
        if (valid) {
          Couponcreate(this.ruleForm)
            .then((res) => {
              if (res.errno != 402) {
                console.log(res)
                this.$notify({
                  title: '添加成功',
                  message: '这是一条成功的提示消息',
                  type: 'success'
                })
                this.$emit('modalSaveEmit')
              } else {
                this.$notify.error({
                  title: '失败',
                  message: res.errmsg
                })
              }
            })
            .catch((err) => {
              console.log(err)

              this.$message.error('添加失败！')
            })
            .finally(() => {
              this.disabled = false
            })
          // console.log(this.ruleForm);
        } else {
          console.log('error submit!!')
          this.disabled = false
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleAvatarSuccess(res, file) {
      this.ruleForm.picUrl = URL.createObjectURL(file.raw)
      this.ruleForm.picUrl = res.data.url.replace(
        'blob:http://localhost:9528',
        this.$store.state.user.url
      )
      console.log(this.ruleForm.picUrl, '////////////////')
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    }
  }
}
</script>

<style lang="scss" scoped>
.addModal::v-deep {
  .el-form-item__label {
    text-align: left;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }

  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
}
</style>